<?php
/**
 * ============================================================================
 * ----------------------------------------------------------------------------
 * 上传类
 * ----------------------------------------------------------------------------
 * ============================================================================
 */
namespace App\Utils;

use App\Models\AttachmentModel;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Intervention\Image\Facades\Image;

class UploadUtil
{
    //上传验证规则
    protected static $uploadValidate = [
        'rule' => [
            'file' => 'file|max:1024*1024*50|mimes:jpg,png,gif,jpeg,rar,zip,avi,mp4,rmvb,3gp,flv,mp3,txt,doc,xls,ppt,pdf,xls,docx,xlsx,doc'
        ],
        'message' => [
            'file.file' => '请确认你的文件格式',
            'file.max' => '文件最大上传大小为50M',
            'file.mimes' => '文件格式限制：jpg,png,gif,jpeg,rar,zip,avi,mp4,rmvb,3gp,flv,mp3,txt,doc,xls,ppt,pdf,xls,docx,xlsx,doc',
        ],
    ];
    protected static $imageValidate = [
        'rule' => [
            'file' => 'file|max:1024*1024*50|mimes:jpg,png,gif,jpeg,bmp,svg'
        ],
        'message' => [
            'file.file' => '请确认你的文件格式',
            'file.max' => '文件最大上传大小为50M',
            'file.mimes' => '文件格式限制：jpg,png,gif,jpeg,bmp,svg',
        ]
    ];
    protected static $videoValidate = [
        'rule' => [
            'file' => 'file|max:1024*1024*100|mimes:avi,rmvb,3gp,flv,mp4'
        ],
        'message' => [
            'file.file' => '请确认你的文件格式',
            'file.max' => '文件最大上传大小为100M',
            'file.mimes' => '文件格式限制：avi,rmvb,3gp,flv,mp4',
        ]
    ];
    protected static $voiceValidate = [
        'rule' => [
            'file' => 'file|max:1024*1024*100|mimes:mp3,wma,wav,amr'
        ],
        'message' => [
            'file.file' => '请确认你的文件格式',
            'file.max' => '文件最大上传大小为100M',
            'file.mimes' => '文件格式限制：mp3,wma,wav,amr',
        ]
    ];

    /**
     * 文件上传
     * @param  boolean $is_thumb 是否压缩
     * @param  int $is_type 数据库储存类型 1、后台 2、前端
     * @return [type]            [description]
     */
    public static function imagesUploads($is_thumb = true, $is_type = 1){
        // 获取表单上传文件
        $files = request()->file();
        if(empty($files)){
            $arr['code'] = 500;
            $arr['msg'] = '请选择上传附件';
            return $arr;
        }
        try {
            ini_set('memory_limit','1024M'); //扩大内存
            $validator = Validator::make($files,static::$imageValidate['rule'],static::$imageValidate['message']);
            if ($validator->fails()) {
                $arr['code'] = 500;
                $arr['msg'] = $validator->errors()->first();
                return $arr;
            }
            $save_name = "";
            foreach($files as $file) {
                $catalog = request()->input("catalog") ? trim(request()->input("catalog")): "temp";
                $save_name = Storage::disk('uploads')->putFile($catalog.'/'.date('Ymd') , $file);
            }
            $res = [];
            $res['satt_dir'] = "";
            if($is_thumb) {
                $res = self::saveThumb($save_name);
                $res['satt_dir'] = $_SERVER['HTTP_ORIGIN']."/".$res['satt_dir'];  //压缩路径
            }else{
                $att_path = public_path('uploads/'. str_replace('\\', '/', $save_name));
                $image = Image::make($att_path);
                $res['width'] = $image->width();
                $res['height'] = $image->height();
                $res['att_type'] = explode('/',$image->mime())[1];
                $res['att_mime'] = $image->mime();
                $res['att_size'] = filesize($att_path);
            }
            $res['att_dir'] = $_SERVER['HTTP_ORIGIN'].'/uploads/'.$save_name;//原路径
            $name = explode("/",str_replace('\\', '/', $save_name));
            $res['name'] = $name[2] ? : "";   //文件名

            $arr['code'] = 200;
            $arr['msg'] = "上传成功";
            $arr['data'] = $res;

            AttachmentModel::attachment($res, $is_type); //存储

            return $arr;
        } catch (\Exception $e) {
            $arr['code'] = 500;
            $arr['msg'] = $e->getMessage();
            return $arr;
        }
    }

    /**
     * 保存缩略图
     * @param  [type]  $filename 文件
     * @param  integer $w        [description]
     * @param  integer $h        [description]
     * @return [type]            [description]
     */
    public static function saveThumb($filename){
        //原图数据
        $att_dir = public_path('uploads/'. str_replace('\\', '/', $filename));
        $size = filesize($att_dir);
        $image = Image::make($att_dir);
        $width = $image->width();
        $height = $image->height();
        //生成缩略图
        $str = explode("/", str_replace('\\', '/', $filename));
        $path = "uploads/{$str[0]}/{$str[1]}/thumb/";
        $save_path = public_path($path);
        if(!file_exists($save_path)) {
            mkdir($save_path,0777,TRUE);
            chmod($save_path,0777);
        }
        $new_file_name = public_path($path).$str[2];
        $image->resize($width, null, function ($constraint) {
            $constraint->aspectRatio();
        })->save($new_file_name);
        $arr = [
            'satt_dir' => $path.$str[2],
            'width' => $width,
            'height' => $height,
            'att_type' => explode('/',$image->mime())[1],
            'att_mime' => $image->mime(),
            'att_size' => $size,
        ];
        return $arr;
    }

    /**
     * 视频上传
     * @return [type]            [description]
     */
    public static function videoUploads(){
        // 获取表单上传文件
        $files = request()->file();
        try{
            ini_set('memory_limit','1024M'); //扩大内存
            $validator = Validator::make($files,static::$uploadValidate['rule'],static::$uploadValidate['message']);
            if ($validator->fails()) {
                $arr['code'] = 500;
                $arr['msg'] = $validator->errors()->first();
                return $arr;
            }
            $save_name = "";
            foreach($files as $file) {
                $catalog = request()->input("catalog") ? trim(request()->input("catalog")): "video";
                $save_name = Storage::disk('uploads')->putFile($catalog.'/'.date('Ymd') , $file);
            }

            $video_img = FfmpegUtil::ffmpegPicture($_SERVER['HTTP_ORIGIN'].'/uploads/'.$save_name,'','',3,'gif',$catalog);

            if($video_img['code'] == 500){
                $arr['code'] = 500;
                $arr['msg'] = $video_img['msg'];
                return $arr;
            }

            if($video_img['pic_path'] && @fopen($video_img['pic_path'],'r')){
                $pic_path = str_replace($_SERVER['HTTP_ORIGIN'],public_path(),$video_img['pic_path']);//获取视频绝对路径
                $image = Image::make($pic_path);

                $res['width'] = $image->width();//视频封面宽
                $res['height'] = $image->height();//视频封面高度
            }

            $res['video_img'] = $video_img['pic_path'] ? : "";//视频封面

            $att_path = $video_img['video_url'];
            $res['att_size'] = filesize($att_path);//视频大小
            $res['att_dir'] = str_replace(public_path(),$_SERVER['HTTP_ORIGIN'],$att_path);//视频相对路径
            $res['att_time'] = secondToTime(HisToS($video_img['video_time']),2);

            $arr['code'] = 200;
            $arr['msg'] = "上传成功";
            $arr['data'] = $res;

            return $arr;

        } catch (\Exception $e) {
            $arr['code'] = 500;
            $arr['msg'] = $e->getMessage();
            return $arr;
        }
    }
}
